'use client';

import { useClientParams, useGlobalState } from '@/hooks';
import { getProductsCount } from '@/services/front';
import {
  filtersToSearchParams,
  parseUrlToFetchParams,
  searchParamsToFilters,
  staticGo,
} from '@/utils/common';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';

const FilterCategories = ({
  paths,
  basePath,
  onChange,
  isLogin,
}: FilterSectionProps) => {
  const [categoriesCounts, setCategoriesCounts] = useState<any[] | null>(null);
  const [title, setTitle] = useState<string>(
    basePath == 'categories' ? 'All Categories' : 'Filter by Categories'
  );
  const [expand, setExpand] = useState(!(!isLogin && basePath != 'categories'));
  const rootId = Number(process.env.NEXT_PUBLIC_ROOT_CATEGORY_ID);
  const { categoryList } = useGlobalState('product');
  const [currPaths, setCurrPaths] = useState(paths);
  const [parentPaths, setParentPaths] = useState('');
  const {
    basePath: c_basePath,
    pathname,
    searchParams,
    queryObject,
    catePaths,
    filterObject,
    categoryObject,
  } = useClientParams();
  // const currentParams = Object.fromEntries(searchParams);
  // const baseFilters = searchParamsToFilters(currentParams);

  const toogleExpand = () => {
    setExpand(e => !e);
  };

  const [loginURL, setLoginURL] = useState('');
  const [signupURL, setSignupURL] = useState('');
  const getLoginURL = () => {
    const url =
      process.env.NEXT_PUBLIC_LOGIN_URL +
      '?return_url=' +
      encodeURIComponent(
        location.origin + '/api/login?backurl=' + window.location.href
      );
    return url;
  };
  const getSignupURL = () => {
    const url = 'https://web.my-company.net.cn/get-started/sign-up';
    return url;
  };
  useEffect(() => {
    setLoginURL(getLoginURL());
    setSignupURL(getSignupURL());
  }, []);

  const getFilterCategories = (
    parent_id: number | null = rootId,
    category_id: number = rootId,
    pathsList: any[] = []
  ) => {
    const result: any[] = [];
    const category_lv1 = categoryList.filter(
      (c: any) => c.parent_id == parent_id
    );
    let c1FocusId = 0;
    if (parent_id != rootId) {
      const L1Cat = categoryList.find((c: any) => c.category_id == parent_id);
      L1Cat &&
        result.push({
          title: 'Shop All ' + L1Cat.title,
          category_id: parent_id,
          format_paths: pathsList.slice(0, 1),
          format_lvl: 0,
          is_current: pathsList?.length == 1,
        });
    }
    category_lv1?.forEach((c1: any) => {
      result.push({
        ...c1,
        format_lvl: 1,
        is_current: category_id == c1.category_id,
      });
      if (category_id == c1.category_id) c1FocusId = c1.category_id;
      if (category_id != rootId) {
        const category_lv2 = categoryList.filter(
          (c: any) => c.parent_id == c1.category_id
        );
        const res: any[] = [];
        let c2FocusId = 0;
        category_lv2?.forEach((c2: any) => {
          res.push({
            ...c2,
            format_lvl: 2,
            is_current: category_id == c2.category_id,
          });
          if (category_id == c2.category_id) c2FocusId = c2.category_id;
        });
        if (c1FocusId == res[0].parent_id || c2FocusId) result.push(...res);
      }
    });
    //console.log('filter>>>>> ', result);
    return result;
  };

  const getIdByFormatTitle = (url_key: string) => {
    const fc = categoryList.find((c: any) => c.url_key == url_key);
    return fc ? fc.category_id : undefined;
  };

  const getCurrentcategoryList = (paths?: any[]) => {
    const pathsList = paths || currPaths || [];
    if (pathsList?.length >= 2) {
      const currParentId = getIdByFormatTitle(pathsList[0]);
      const currId = getIdByFormatTitle(pathsList[pathsList.length - 1]);
      return getFilterCategories(currParentId, currId, pathsList);
    } else if (pathsList?.length) {
      const currParentId = getIdByFormatTitle(pathsList[0]);
      // const currId = getIdByFormatTitle(pathsList[pathsList.length - 1]);
      return getFilterCategories(currParentId, undefined, pathsList);
    } else {
      return getFilterCategories(undefined, undefined);
    }
  };
  const getCurCatsRef = useRef(getCurrentcategoryList);
  getCurCatsRef.current = getCurrentcategoryList;
  // setFilterCategories(getCurCatsRef.current());

  const serverFilterCategories = getCurrentcategoryList(paths);
  const [filterCategories, setFilterCategories] = useState<any[]>(
    serverFilterCategories
  );

  const handleCategoryClick = (e: any) => {
    const elm = e.currentTarget;
    let pathString = pathname;
    const newParams: Obj = { ...queryObject }; //filtersToSearchParams(filterObject);
    if (elm) {
      //onChange && onChange('categorylink', { ...elm.dataset });
      const data = elm.dataset;
      if (c_basePath == 'catalogsearch') {
        if (Number(data.catid) == rootId) {
          delete newParams.cat;
        } else {
          newParams['cat'] = Number(data.catid);
        }
      } else {
        pathString = `/${basePath}` + (data.value ? `/${data.value}` : '');
      }
      if (newParams.p) delete newParams.p;
      // console.log(basePath, data.value, pathString, newParams, pathname);
      staticGo(pathString, newParams);
      onChange && onChange();
      if (pathString === pathname) changePathRef.current();
    }
  };
  const handleCategoryBack = (e: any) => {
    const elm = e.currentTarget;
    if (elm) {
      const data = elm.dataset;
      const tPath =
        c_basePath == 'categories'
          ? []
          : data.value
            ? data.value.split('/')
            : [];
      // console.log(data, data.value, tPath);
      setCurrPaths(tPath);
      const newTree = getCurCatsRef.current(tPath);
      setFilterCategories(newTree);
      fillNumberRef.current(newTree);
      if (c_basePath !== 'categories') {
        const parentCategory = categoryList.find(
          (c: any) => c.format_paths == data.value
        );
        parentCategory &&
          handleCategoryClick({
            currentTarget: {
              dataset: {
                catid: parentCategory.category_id,
                value: parentCategory.format_paths,
              },
            },
          });
      }
    }
  };

  const fillNumberToList = (newTree?: any[]) => {
    // console.log('🎁🎁🎁', filterCategories, categoriesCounts);
    const currCategories = newTree || filterCategories;
    if (categoriesCounts && currCategories?.length) {
      const numberFilterCategories = currCategories.map((fc: any) => ({
        ...fc,
        number:
          categoriesCounts?.find((cc: any) => cc.category_id == fc.category_id)
            ?.count || 0,
      }));
      setFilterCategories(numberFilterCategories);
    }
  };
  const fillNumberRef = useRef(fillNumberToList);
  fillNumberRef.current = fillNumberToList;
  useEffect(() => {
    categoriesCounts && fillNumberRef.current();
  }, [categoriesCounts]);

  const changePathAction = () => {
    if (!c_basePath) return;
    let cPaths = catePaths;
    let cCat: Category | null | undefined = categoryObject;
    if (c_basePath == 'catalogsearch' && queryObject.cat) {
      cCat = categoryList.find((c: any) => c.category_id == queryObject.cat);
      if (cCat) cPaths = cCat.format_paths.split('/');
    }
    setCurrPaths(cPaths);
    //========================
    // console.log('categoryObject:::>>', cCat);
    setTitle(
      c_basePath == 'categories'
        ? 'All Categories'
        : (cCat as Category)?.format_paths.split('/').length >= 3
          ? 'Filter by Sub-Categories'
          : 'Filter by Categories'
    );
    //========================
    const pPath = cPaths.slice(0, -1).join('/');
    setParentPaths(pPath);
    const newTree = getCurCatsRef.current(cPaths);
    setFilterCategories(newTree);
    fillNumberRef.current(newTree);
  };
  const changePathRef = useRef(changePathAction);
  changePathRef.current = changePathAction;

  useEffect(() => {
    changePathRef.current();
    queryCountsRef.current();
    // console.log(c_basePath, catePaths, queryObject);
  }, [c_basePath, catePaths, queryObject]);
  //=================================================================================
  const tempRef: Obj = useRef({});
  const queryCounts = async () => {
    const queryParams = parseUrlToFetchParams(
      c_basePath,
      catePaths,
      queryObject,
      categoryList
    );
    if (isLogin) {
      delete queryParams.category_id;
      delete queryParams.sort_by;
      delete queryParams.sort_order;
      delete queryParams.page_no;
      if (JSON.stringify(queryParams) !== tempRef.prevQueryParams) {
        setCategoriesCounts(null);
        tempRef.prevQueryParams = JSON.stringify(queryParams);
        const counts = await getProductsCount(queryParams).catch(e => {
          void e;
        });
        setCategoriesCounts(counts || []);
      }
    }
  };
  const queryCountsRef = useRef(queryCounts);
  queryCountsRef.current = queryCounts;

  return (
    <div className="side-section">
      <div className="side-section-title no-mouse-event">
        <span
          className={
            'side-section-title-text' +
            (currPaths?.length ? ' title-text-with-back' : '')
          }
          data-value={currPaths?.slice(0, -1).join('/')}
          {...{ onClick: handleCategoryBack }}
        >
          <span className="side-section-title-back iconfont icon-arrow-left-long"></span>
          {title}
        </span>
        <span
          className={`side-section-expand-icon iconfont icon-expand-line ${expand ? 'expand-icon-up' : 'expand-icon-down'}`}
          onClick={toogleExpand}
        ></span>
      </div>
      <div
        className={`side-section-content thin-scroll-bar ${expand ? 'content-expand' : 'content-collapse'}`}
      >
        <div className="side-section-list">
          {!isLogin && c_basePath != 'categories' ? (
            <div className="side-section-login-tips">
              <Link href={signupURL}>Sign up</Link> or{' '}
              <Link href={loginURL}>Login</Link> to use this feature.
            </div>
          ) : (
            filterCategories?.map(
              (item: any, index) =>
                (item.number !== 0 || item.format_lvl == 0) && (
                  <div className="side-section-item" key={index}>
                    <div
                      data-value={`${item.format_paths}`}
                      data-catid={`${item.category_id}`}
                      onClick={handleCategoryClick}
                      className={
                        'side-section-item-link' +
                        (item.format_lvl == 2
                          ? ' side-section-item-sub'
                          : item.format_lvl == 0
                            ? ' side-section-item-parent'
                            : '') +
                        (item.is_current
                          ? ' side-section-item-link-current'
                          : '')
                      }
                    >
                      {item.title}
                    </div>
                    {/* </Link> */}
                    {item.number != undefined && (
                      <span className="side-section-item-number">
                        ({item.number})
                      </span>
                    )}
                  </div>
                )
            )
          )}
        </div>
      </div>
    </div>
  );
};

export default FilterCategories;
